package com.zhouhailin.shirospringbootdemo.shiro.realm;

import com.zhouhailin.shirospringbootdemo.entity.Permission;
import com.zhouhailin.shirospringbootdemo.entity.User;
import com.zhouhailin.shirospringbootdemo.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * 自定义Realm
 *
 * @Author zhouhailin
 * @date 2023/1/4 19:47
 */
//@Component
public class CustomerRealm extends AuthorizingRealm {
    private static final Logger logger = LoggerFactory.getLogger(CustomerRealm.class);

    @Resource
    private UserService userService;

    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("进入授权方法--------------------------");

        // 1、获取身份信息
        String primaryPrincipal = (String) principalCollection.getPrimaryPrincipal();

        // 2、根据身份信息获取角色和权限信息
        User user = userService.findByUserName(primaryPrincipal);

        // 3、授权角色信息
        if (!CollectionUtils.isEmpty(user.getRoles())) {
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            user.getRoles().forEach(role -> {
                // 添加角色
                simpleAuthorizationInfo.addRole(role.getRoleName());
                logger.info("用户具有的角色：[{}]", role.getRoleName());
                List<Permission> permissions = userService.findPermsByRoleId(role.getId());
                if (!CollectionUtils.isEmpty(permissions)) {
                    permissions.forEach(permission -> {
                        // 给角色添加权限
                        simpleAuthorizationInfo.addStringPermission(permission.getPermissionName());
                        logger.info("该角色拥有的权限：[{}]", permission.getPermissionName());
                    });
                }
            });
            return simpleAuthorizationInfo;
        }
        return null;
    }

    /**
     * 认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//        // 获取身份信息
//        String principal = (String) authenticationToken.getPrincipal();
//
//        if ("zhangsan".equals(principal)) {
//            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//            info.addRole("admin");
//            info.addRole("user");
//            info.addStringPermission("user:find:*");
//            info.addStringPermission("admin:*");
//            return info;
//
//        }

        System.out.println("进入认证方法===================");
        String principal = (String) authenticationToken.getPrincipal();
//        if ("zhouhailin".equals(principal)) {
//            return new SimpleAuthenticationInfo(principal, "123", this.getName());
//        }

        User user = userService.findByUserName(principal);
        if (null == user) {
            throw new AccountException("不存在此用户！");
        }

        // 获取盐值
//        ByteSource salt = ByteSource.Util.bytes(principal);
        return new SimpleAuthenticationInfo(user.getUsername(), "123", this.getName());
    }
}
